package com.zed.game.answer.fetures;

import cn.hutool.core.io.IoUtil;
import com.zed.api.common.Serializer;
import com.zed.api.games.answer.show.AnswerShowWorld;

import java.io.*;

/**
 * 对{@link com.zed.api.games.answer.show.AnswerShowWorld}的序列化器
 *
 * @author Zed
 */
class AnsweShowWorldSerializer implements Serializer {


    @Override
    public byte[] serial(Object target) throws IOException {
        if (target == null) return new byte[0];

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(os);
            oos.writeObject(target);
            return os.toByteArray();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (Exception e) {
                }
            }

            try {
                os.close();
            } catch (Exception e) {
            }
        }
    }

    @Override
    public AnswerShowWorld deSerial(byte[] bytes) throws IOException, ClassNotFoundException {
        if (bytes == null) return null;
        if (bytes.length == 0) return null;

        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(is);
            return (AnswerShowWorld) ois.readObject();
        } finally {
            IoUtil.close(ois);
            IoUtil.close(is);
        }
    }

}
